#include "mycallback.h"

MyCallback::MyCallback(QObject *parent) :
    Sbs2Callback(parent)
{
    isInPlayback = 0;
    playback1 = 0;
    playback2 = 0;

}

void MyCallback::getData(Sbs2Packet *packet)
{
    currentPacketCounter = packet->counter;
    ++ currentPacket;

    thisPacket = packet;
    sbs2DataHandler->setThisPacket(thisPacket);
    sbs2DataHandler->record();

    if (playback1 && currentPacket%256 == 0)
    {
        isInPlayback = 1;
        //emit playSingle();
        //QtConcurrent::run(audioPlayer,&NativeAudioPlayer::playSingle);
        audioPlayer->playSingle();
    }
    if (playback1)
    {
        checkPlaybackStatus();
    }


}

void MyCallback::checkPlaybackStatus()
{
    if (playback2)
        isInPlayback = 1;

    if (!isInPlayback || audioPlayer == 0)
        return;

    playbackPosition = audioPlayer->playbackPosition();
    if (playbackPosition > 0)
    {
        currentText =  QString::number(playbackPosition).append(" ").append(QString::number(QDateTime::currentMSecsSinceEpoch())).append(" ").append(QString::number(currentPacket-sbs2DataHandler->getPacketZero()+1));
        fullText.append(currentText).append("\n");

        __android_log_write(ANDROID_LOG_INFO, "SBS2",currentText.toStdString().c_str());
        //insertIntoMetaFile(currentText);
        //qDebug() << playbackPosition << QDateTime::currentMSecsSinceEpoch() << QString::number(currentPacket);
        isInPlayback = 0;
    }


}

void MyCallback::save()
{
    insertIntoMetaFile(fullText);
}

//Packet-based
void MyCallback::startPlayback1()
{

    playback1 = 1;
}

void MyCallback::startPlayback2()
{
    playback2 = 1;
    isInPlayback = 1;
    QTimer* t = new QTimer();
    connect(t,SIGNAL(timeout()),this,SLOT(checkPlaybackStatus()));
    t->start(1000);

    if (audioPlayer)
        audioPlayer->play();



}
